package com.yonglian.management.web.rest;

import static com.yonglian.management.domain.ActivityPropertyAsserts.*;
import static com.yonglian.management.web.rest.TestUtil.createUpdateProxyForBean;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yonglian.management.IntegrationTest;
import com.yonglian.management.domain.ActivityProperty;
import com.yonglian.management.domain.enumeration.ActivityPropertyType;
import com.yonglian.management.repository.ActivityPropertyRepository;
import jakarta.persistence.EntityManager;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;

/**
 * Integration tests for the {@link ActivityPropertyResource} REST controller.
 */
@IntegrationTest
@AutoConfigureMockMvc
@WithMockUser
class ActivityPropertyResourceIT {

    private static final String DEFAULT_PROPERTY_NAME = "AAAAAAAAAA";
    private static final String UPDATED_PROPERTY_NAME = "BBBBBBBBBB";

    private static final String DEFAULT_PROPERTY_VALUE = "AAAAAAAAAA";
    private static final String UPDATED_PROPERTY_VALUE = "BBBBBBBBBB";

    private static final String DEFAULT_PROPERTY_REMARK = "AAAAAAAAAA";
    private static final String UPDATED_PROPERTY_REMARK = "BBBBBBBBBB";

    private static final ActivityPropertyType DEFAULT_PROPERTY_TYPE = ActivityPropertyType.TEXT;
    private static final ActivityPropertyType UPDATED_PROPERTY_TYPE = ActivityPropertyType.IMAGE;

    private static final Integer DEFAULT_ORDER_NO = 1;
    private static final Integer UPDATED_ORDER_NO = 2;

    private static final String ENTITY_API_URL = "/api/activity-properties";
    private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}";

    private static Random random = new Random();
    private static AtomicLong longCount = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE));

    @Autowired
    private ObjectMapper om;

    @Autowired
    private ActivityPropertyRepository activityPropertyRepository;

    @Autowired
    private EntityManager em;

    @Autowired
    private MockMvc restActivityPropertyMockMvc;

    private ActivityProperty activityProperty;

    /**
     * Create an entity for this test.
     *
     * This is a static method, as tests for other entities might also need it,
     * if they test an entity which requires the current entity.
     */
    public static ActivityProperty createEntity(EntityManager em) {
        ActivityProperty activityProperty = new ActivityProperty()
            .propertyName(DEFAULT_PROPERTY_NAME)
            .propertyValue(DEFAULT_PROPERTY_VALUE)
            .propertyRemark(DEFAULT_PROPERTY_REMARK)
            .propertyType(DEFAULT_PROPERTY_TYPE)
            .orderNo(DEFAULT_ORDER_NO);
        return activityProperty;
    }

    /**
     * Create an updated entity for this test.
     *
     * This is a static method, as tests for other entities might also need it,
     * if they test an entity which requires the current entity.
     */
    public static ActivityProperty createUpdatedEntity(EntityManager em) {
        ActivityProperty activityProperty = new ActivityProperty()
            .propertyName(UPDATED_PROPERTY_NAME)
            .propertyValue(UPDATED_PROPERTY_VALUE)
            .propertyRemark(UPDATED_PROPERTY_REMARK)
            .propertyType(UPDATED_PROPERTY_TYPE)
            .orderNo(UPDATED_ORDER_NO);
        return activityProperty;
    }

    @BeforeEach
    public void initTest() {
        activityProperty = createEntity(em);
    }

    @Test
    @Transactional
    void createActivityProperty() throws Exception {
        long databaseSizeBeforeCreate = getRepositoryCount();
        // Create the ActivityProperty
        var returnedActivityProperty = om.readValue(
            restActivityPropertyMockMvc
                .perform(
                    post(ENTITY_API_URL)
                        .with(csrf())
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(om.writeValueAsBytes(activityProperty))
                )
                .andExpect(status().isCreated())
                .andReturn()
                .getResponse()
                .getContentAsString(),
            ActivityProperty.class
        );

        // Validate the ActivityProperty in the database
        assertIncrementedRepositoryCount(databaseSizeBeforeCreate);
        assertActivityPropertyUpdatableFieldsEquals(returnedActivityProperty, getPersistedActivityProperty(returnedActivityProperty));
    }

    @Test
    @Transactional
    void createActivityPropertyWithExistingId() throws Exception {
        // Create the ActivityProperty with an existing ID
        activityProperty.setId(1L);

        long databaseSizeBeforeCreate = getRepositoryCount();

        // An entity with an existing ID cannot be created, so this API call must fail
        restActivityPropertyMockMvc
            .perform(
                post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(activityProperty))
            )
            .andExpect(status().isBadRequest());

        // Validate the ActivityProperty in the database
        assertSameRepositoryCount(databaseSizeBeforeCreate);
    }

    @Test
    @Transactional
    void checkPropertyNameIsRequired() throws Exception {
        long databaseSizeBeforeTest = getRepositoryCount();
        // set the field null
        activityProperty.setPropertyName(null);

        // Create the ActivityProperty, which fails.

        restActivityPropertyMockMvc
            .perform(
                post(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(activityProperty))
            )
            .andExpect(status().isBadRequest());

        assertSameRepositoryCount(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    void getAllActivityProperties() throws Exception {
        // Initialize the database
        activityPropertyRepository.saveAndFlush(activityProperty);

        // Get all the activityPropertyList
        restActivityPropertyMockMvc
            .perform(get(ENTITY_API_URL + "?sort=id,desc"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.[*].id").value(hasItem(activityProperty.getId().intValue())))
            .andExpect(jsonPath("$.[*].propertyName").value(hasItem(DEFAULT_PROPERTY_NAME)))
            .andExpect(jsonPath("$.[*].propertyValue").value(hasItem(DEFAULT_PROPERTY_VALUE)))
            .andExpect(jsonPath("$.[*].propertyRemark").value(hasItem(DEFAULT_PROPERTY_REMARK)))
            .andExpect(jsonPath("$.[*].propertyType").value(hasItem(DEFAULT_PROPERTY_TYPE.toString())))
            .andExpect(jsonPath("$.[*].orderNo").value(hasItem(DEFAULT_ORDER_NO)));
    }

    @Test
    @Transactional
    void getActivityProperty() throws Exception {
        // Initialize the database
        activityPropertyRepository.saveAndFlush(activityProperty);

        // Get the activityProperty
        restActivityPropertyMockMvc
            .perform(get(ENTITY_API_URL_ID, activityProperty.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
            .andExpect(jsonPath("$.id").value(activityProperty.getId().intValue()))
            .andExpect(jsonPath("$.propertyName").value(DEFAULT_PROPERTY_NAME))
            .andExpect(jsonPath("$.propertyValue").value(DEFAULT_PROPERTY_VALUE))
            .andExpect(jsonPath("$.propertyRemark").value(DEFAULT_PROPERTY_REMARK))
            .andExpect(jsonPath("$.propertyType").value(DEFAULT_PROPERTY_TYPE.toString()))
            .andExpect(jsonPath("$.orderNo").value(DEFAULT_ORDER_NO));
    }

    @Test
    @Transactional
    void getNonExistingActivityProperty() throws Exception {
        // Get the activityProperty
        restActivityPropertyMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound());
    }

    @Test
    @Transactional
    void putExistingActivityProperty() throws Exception {
        // Initialize the database
        activityPropertyRepository.saveAndFlush(activityProperty);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the activityProperty
        ActivityProperty updatedActivityProperty = activityPropertyRepository.findById(activityProperty.getId()).orElseThrow();
        // Disconnect from session so that the updates on updatedActivityProperty are not directly saved in db
        em.detach(updatedActivityProperty);
        updatedActivityProperty
            .propertyName(UPDATED_PROPERTY_NAME)
            .propertyValue(UPDATED_PROPERTY_VALUE)
            .propertyRemark(UPDATED_PROPERTY_REMARK)
            .propertyType(UPDATED_PROPERTY_TYPE)
            .orderNo(UPDATED_ORDER_NO);

        restActivityPropertyMockMvc
            .perform(
                put(ENTITY_API_URL_ID, updatedActivityProperty.getId())
                    .with(csrf())
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(om.writeValueAsBytes(updatedActivityProperty))
            )
            .andExpect(status().isOk());

        // Validate the ActivityProperty in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertPersistedActivityPropertyToMatchAllProperties(updatedActivityProperty);
    }

    @Test
    @Transactional
    void putNonExistingActivityProperty() throws Exception {
        long databaseSizeBeforeUpdate = getRepositoryCount();
        activityProperty.setId(longCount.incrementAndGet());

        // If the entity doesn't have an ID, it will throw BadRequestAlertException
        restActivityPropertyMockMvc
            .perform(
                put(ENTITY_API_URL_ID, activityProperty.getId())
                    .with(csrf())
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(om.writeValueAsBytes(activityProperty))
            )
            .andExpect(status().isBadRequest());

        // Validate the ActivityProperty in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void putWithIdMismatchActivityProperty() throws Exception {
        long databaseSizeBeforeUpdate = getRepositoryCount();
        activityProperty.setId(longCount.incrementAndGet());

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restActivityPropertyMockMvc
            .perform(
                put(ENTITY_API_URL_ID, longCount.incrementAndGet())
                    .with(csrf())
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(om.writeValueAsBytes(activityProperty))
            )
            .andExpect(status().isBadRequest());

        // Validate the ActivityProperty in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void putWithMissingIdPathParamActivityProperty() throws Exception {
        long databaseSizeBeforeUpdate = getRepositoryCount();
        activityProperty.setId(longCount.incrementAndGet());

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restActivityPropertyMockMvc
            .perform(
                put(ENTITY_API_URL).with(csrf()).contentType(MediaType.APPLICATION_JSON).content(om.writeValueAsBytes(activityProperty))
            )
            .andExpect(status().isMethodNotAllowed());

        // Validate the ActivityProperty in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void partialUpdateActivityPropertyWithPatch() throws Exception {
        // Initialize the database
        activityPropertyRepository.saveAndFlush(activityProperty);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the activityProperty using partial update
        ActivityProperty partialUpdatedActivityProperty = new ActivityProperty();
        partialUpdatedActivityProperty.setId(activityProperty.getId());

        partialUpdatedActivityProperty.propertyName(UPDATED_PROPERTY_NAME).orderNo(UPDATED_ORDER_NO);

        restActivityPropertyMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, partialUpdatedActivityProperty.getId())
                    .with(csrf())
                    .contentType("application/merge-patch+json")
                    .content(om.writeValueAsBytes(partialUpdatedActivityProperty))
            )
            .andExpect(status().isOk());

        // Validate the ActivityProperty in the database

        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertActivityPropertyUpdatableFieldsEquals(
            createUpdateProxyForBean(partialUpdatedActivityProperty, activityProperty),
            getPersistedActivityProperty(activityProperty)
        );
    }

    @Test
    @Transactional
    void fullUpdateActivityPropertyWithPatch() throws Exception {
        // Initialize the database
        activityPropertyRepository.saveAndFlush(activityProperty);

        long databaseSizeBeforeUpdate = getRepositoryCount();

        // Update the activityProperty using partial update
        ActivityProperty partialUpdatedActivityProperty = new ActivityProperty();
        partialUpdatedActivityProperty.setId(activityProperty.getId());

        partialUpdatedActivityProperty
            .propertyName(UPDATED_PROPERTY_NAME)
            .propertyValue(UPDATED_PROPERTY_VALUE)
            .propertyRemark(UPDATED_PROPERTY_REMARK)
            .propertyType(UPDATED_PROPERTY_TYPE)
            .orderNo(UPDATED_ORDER_NO);

        restActivityPropertyMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, partialUpdatedActivityProperty.getId())
                    .with(csrf())
                    .contentType("application/merge-patch+json")
                    .content(om.writeValueAsBytes(partialUpdatedActivityProperty))
            )
            .andExpect(status().isOk());

        // Validate the ActivityProperty in the database

        assertSameRepositoryCount(databaseSizeBeforeUpdate);
        assertActivityPropertyUpdatableFieldsEquals(
            partialUpdatedActivityProperty,
            getPersistedActivityProperty(partialUpdatedActivityProperty)
        );
    }

    @Test
    @Transactional
    void patchNonExistingActivityProperty() throws Exception {
        long databaseSizeBeforeUpdate = getRepositoryCount();
        activityProperty.setId(longCount.incrementAndGet());

        // If the entity doesn't have an ID, it will throw BadRequestAlertException
        restActivityPropertyMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, activityProperty.getId())
                    .with(csrf())
                    .contentType("application/merge-patch+json")
                    .content(om.writeValueAsBytes(activityProperty))
            )
            .andExpect(status().isBadRequest());

        // Validate the ActivityProperty in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void patchWithIdMismatchActivityProperty() throws Exception {
        long databaseSizeBeforeUpdate = getRepositoryCount();
        activityProperty.setId(longCount.incrementAndGet());

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restActivityPropertyMockMvc
            .perform(
                patch(ENTITY_API_URL_ID, longCount.incrementAndGet())
                    .with(csrf())
                    .contentType("application/merge-patch+json")
                    .content(om.writeValueAsBytes(activityProperty))
            )
            .andExpect(status().isBadRequest());

        // Validate the ActivityProperty in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void patchWithMissingIdPathParamActivityProperty() throws Exception {
        long databaseSizeBeforeUpdate = getRepositoryCount();
        activityProperty.setId(longCount.incrementAndGet());

        // If url ID doesn't match entity ID, it will throw BadRequestAlertException
        restActivityPropertyMockMvc
            .perform(
                patch(ENTITY_API_URL)
                    .with(csrf())
                    .contentType("application/merge-patch+json")
                    .content(om.writeValueAsBytes(activityProperty))
            )
            .andExpect(status().isMethodNotAllowed());

        // Validate the ActivityProperty in the database
        assertSameRepositoryCount(databaseSizeBeforeUpdate);
    }

    @Test
    @Transactional
    void deleteActivityProperty() throws Exception {
        // Initialize the database
        activityPropertyRepository.saveAndFlush(activityProperty);

        long databaseSizeBeforeDelete = getRepositoryCount();

        // Delete the activityProperty
        restActivityPropertyMockMvc
            .perform(delete(ENTITY_API_URL_ID, activityProperty.getId()).with(csrf()).accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isNoContent());

        // Validate the database contains one less item
        assertDecrementedRepositoryCount(databaseSizeBeforeDelete);
    }

    protected long getRepositoryCount() {
        return activityPropertyRepository.count();
    }

    protected void assertIncrementedRepositoryCount(long countBefore) {
        assertThat(countBefore + 1).isEqualTo(getRepositoryCount());
    }

    protected void assertDecrementedRepositoryCount(long countBefore) {
        assertThat(countBefore - 1).isEqualTo(getRepositoryCount());
    }

    protected void assertSameRepositoryCount(long countBefore) {
        assertThat(countBefore).isEqualTo(getRepositoryCount());
    }

    protected ActivityProperty getPersistedActivityProperty(ActivityProperty activityProperty) {
        return activityPropertyRepository.findById(activityProperty.getId()).orElseThrow();
    }

    protected void assertPersistedActivityPropertyToMatchAllProperties(ActivityProperty expectedActivityProperty) {
        assertActivityPropertyAllPropertiesEquals(expectedActivityProperty, getPersistedActivityProperty(expectedActivityProperty));
    }

    protected void assertPersistedActivityPropertyToMatchUpdatableProperties(ActivityProperty expectedActivityProperty) {
        assertActivityPropertyAllUpdatablePropertiesEquals(
            expectedActivityProperty,
            getPersistedActivityProperty(expectedActivityProperty)
        );
    }
}
